class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> res{};
        int n = nums.size();
        for(int i = 0; i + 3 < n; i++)
        {
            // 大幅度提高效率的两行剪枝
            if((nums[i] + nums[i+1] + nums[i+2] + nums[i+3]) > target) break;
            if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target) continue;
            
            for(int j = i + 1; j + 2 < n; j++)
            {
                int left = j + 1, right = n - 1;
                while(left < right)
                {
                    if(nums[left] + nums[right] + nums[i] + nums[j] > target)
                        right--;
                    else if(nums[left] + nums[right] + nums[i] + nums[j] < target)
                        left++;
                    else
                    {
                        vector<int> temp {nums[i], nums[j], nums[left], nums[right]};
                        res.push_back(temp);
                        while(left < right && nums[left] == temp[2]) left++;
                        while(right > left && nums[right] == temp[3]) right--;
                    }
                }
                
                while(j + 3 < n && nums[j + 1] == nums[j])
                    j++;
            }
            while(i + 4 < n && nums[i + 1] == nums[i])
                i++;
        }
        return res;
    }
};
